﻿package com.cilico.components;

import java.util.ArrayList;
import java.util.Vector;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cilico.ConfigManager;
import com.cilico.Mid;
import com.cilico.R;
import com.cilico.utils.Constant;
import com.cilico.utils.ConstantRepository;
import com.cilico.utils.Utils;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;
import com.cilico.wheel.ArrayWheelAdapter;
import com.cilico.wheel.WheelView;

public class Select extends TextView implements Component {
	FormLayout formLayout_;
	private static final int SELECT_FONT_SIZE_DEFAULT = 15;
	public CssStyle cssStyle_;
	TextPaint font_;
	final static int maxWidth_ = 250; // 定义弹出界面的最大宽度
	final static int maxHeight_ = 30;
	final int textBlank_ = 0; // 字符留白
	int width_;
	int height_;
	/** Variables for item drop down menu */
	private int ddmSize_;
	/** In this vector contains all items text of this dropdownMenu */
	public Vector<Option> dropdownMenuText_;
	/** In this vector contains all options */
	public Vector<Option> optionV_;
	String groupN_;
	private int ddmMaxWidth_;
	boolean ddmShown_;
	private boolean isInTable_; // 该控件是否在表格里
	public static int textColor_ = Color.BLACK;
	public String textAlign_;
	public int indStar_ = 0; // the index start to paint.
	public int currentMenu_;
	// 下拉框控件弹出框背景色默认色值
	public static int bgColor_ = 0xFF5A8AB5;
	// 改变量保证界面上始终只有一个由下拉框控件触发的弹出框出现
	public static boolean ISRUNNING;
	// 服务端来的save属性，标志该控件的选中项需要被存储
	public boolean attrSave_;
	public boolean attrTrueSave_;
	private int ddmTotalHeight_;
	Bitmap arrImg_;
	private static Bitmap comboboxBitmap_;
	static Bitmap dropdownIcon_;
	static Bitmap arrowIcon_;
	String selectIcon_;
	String isEncrypt_;
	private static BaseView bv_;
	protected static final int Y_MARGIN = 1; // Margins used when rendering text.
	public String attrName_ = "";
	public String attrRName_ = "";
	public String attrValue_ = "";
	public String attrAccessory_;
	public String form_;
	public String selectName_;
	
	// 此属性如果有值，则下拉框更换选项后执行网络请求更新整个页面的流程
	public String actionUrl_;
	public String optionValue_;//只用于触发网络请求的select
	public String text_;
	public String tableName_;
	public String[] relaEnable_;
	public String[] relaDisable_;
	public String[] relaVisible_;
	public String[] relaInvisible_;
	public Bitmap[] backgroundBitmap_;
	public boolean isCombobox_;
	public String combobxOptionValueKey_;
	public int offsetLength = 0;//select控件左边的控件的宽度＋15
	private int selectMaxWidth_ = 0;//select能够完全显示的最大宽
	
	
	private String [ ] dayNames = {"今天", "明天", "后天"};
	private String [ ] hourNames = {"0点", "1点", "2点", "3点", "4点", "5点", "6点", "7点", "8点", "9点", "10点", "11点", "12点", "13点", "14点", "15点", "16点", "17点", "18点", "19点", "20点", "21点", "22点", "23点"};
	private String [ ] minNames = {"00分", "15分", "30分", "45分"};
	boolean initDataComplete; // 数据完成初始化
	private static AlertDialog pickerDialog;
	private int visiableItems = 0;
	private LinearLayout pickerLayout; // 最外层
	private LinearLayout pickerContainer; // 日时分容器
	private LinearLayout titleLayout; // 标题栏
	public WheelView dayPicker;
	public WheelView hourPicker;
	public WheelView minPicker;
	int dayCurrentItem = 1; //日默认显示第几个
	
	public static class SelectView {
		// 该界面的控件集合
		View[] views_;
		ListView listView_;
		String[] text_;

		LinearLayout ll_;
		// 垂直居中对其管理器，只是让下拉框显示出来的控件作垂直居中作用
		LinearLayout llCenterVertical_;
		ScrollView sc_;
		// 弹出框总管理器
		SelectLinearLayout sll_;

		// 改变量主要用于取消警告框
		public Dialog ad_;

		public static SelectView selectV;

		public static Select select_;

		public SelectView() {
			// TODO Auto-generated constructor stub

		}

		public static SelectView getInstance(Context arg0, View[] views) {
			if (null == selectV) {
				selectV = new SelectView();
			}
			selectV.init(arg0, views);
			return selectV;
		}

		public static void setRelaVisibility() {
		}
			
		private void init(Context arg0, View[] views) {
			// TODO Auto-generated method stub
			// 赋空ad_，否则在弹出界面按BACK键再点击下拉框会出现弹出框无内容情况
			ad_ = null;
			views_ = views;
			int size = views.length;
			View view;
			if (null == backgroundImg_) {
				backgroundImg_ = Utils.getScaledBitmap(arg0.getResources(), R.drawable.selectb);
			}
			if (comboboxBitmap_ == null) {
				comboboxBitmap_ = Utils.getScaledBitmap(arg0.getResources(), R.drawable.comboboxdel);
			}
			// 初始化垂直滚动域
			if (null == sc_) {
				sc_ = new ScrollView(arg0, null, R.style.scrollstyle);
			}
			// option的管理器
			if (null == ll_) {
				ll_ = new LinearLayout(arg0);
			}
			ll_.setOrientation(LinearLayout.VERTICAL);
			ll_.setGravity(Gravity.LEFT);

			if (null == llCenterVertical_) {
				llCenterVertical_ = new LinearLayout(arg0);
				llCenterVertical_.setGravity(Gravity.CENTER_VERTICAL);
				llCenterVertical_.setLayoutParams(new LayoutParams(Utils.getScaledValue(Select.maxWidth_),
						backgroundImg_.getHeight() - (Utils.getScaledValue(Select.maxHeight_) << 1)));
			}

			if (null == sll_) {
				sll_ = new SelectLinearLayout(arg0);
			}

			sc_.removeAllViews();
			ll_.removeAllViews();
			llCenterVertical_.removeAllViews();
			sll_.removeAllViews();

			for (int i = 0; i < size; i++) {
				view = views[i];
				// 将非输入控件添加至垂直管理器，用于添加至滑动域用
				ll_.addView(view);
			}

			ViewGroup vg;
			vg = (ViewGroup) sll_.getParent();
			// 由于引用的ll_管理器唯一，如果此处不将管理器清空，Alert又重新设置该管理器的时候会报管理器已设置（添加）异常
			if (null != vg)
				vg.removeAllViews();

			// 将非包含输入控件的管理器添加至滑动域，方便滑动查看浏览
			llCenterVertical_.addView(sc_);
			sc_.addView(ll_);
			sll_.addView(llCenterVertical_);
			((BaseView) arg0).onCreateSelectDialog((BaseView) arg0, sll_);
		}

		public void setSelectView(Select select) {
			// TODO Auto-generated method stub
			select_ = select;
		}

	}

	/**
	 * label_: display text value_: transfer value group_: If a select has a group attribute, once it's selected, other
	 * selects in the same page should be updated. ref_: If a option has a ref attribute, it should not be displayed in
	 * the select unless its reference group has been selected.
	 */
	public static final class Option extends TextView implements Component {
		public String selectSort_;
		public String sortKey_;
		public String label_;
		public String value_;
		public String group_;
		public String ref_;
		public String select_;
		public String[] relaEnable_;
		public String[] relaDisable_;
		public String[] relaVisible_;
		public String[] relaInvisible_;
		public Select selt_;
		private static final int ROW_TOUCH_BG_COLOR = 0xff2762e1;

		Option(Context context, String l) {
			super(context);
			label_ = l;
			this.setText(label_);
			this.setFocusable(true);
			this.setFocusableInTouchMode(true);
			this.setEllipsize(TruncateAt.END);
			this.setSingleLine();
		}

		public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			setMeasuredDimension(Utils.getScaledValue(maxWidth_), Utils.getScaledValue(maxHeight_));
		}

		void setLabel(String label) {
			label_ = label;
			this.setText(label_);
		}

		void setValue(String value) {
			value_ = value;
		}

		public void settleComponetOption(BaseView bv, boolean isWorked, int i) {
			// TODO Auto-generated method stub
			Utils.settleComponetsChild(bv, isWorked, relaEnable_, relaDisable_, relaVisible_, relaInvisible_, this);
		}

		// 设置的父系控件控件
		void setParent(Select selt) {
			selt_ = selt;
		}

		private void setSelectView() {
			try {
				Select.Option option = SelectView.select_.getCurrentOption();
				SelectView.select_.setText(option.label_);
				SelectView.selectV.ad_.dismiss();
				Select.ISRUNNING = false;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Utils.printException(e);
			}
		}
		
		private void setTextField() {
			Select.Option option = SelectView.select_.getCurrentOption();
			if((mTextField.staticTextField_.mask_)&&(option.value_!=null)){
				mTextField.staticTextField_.attrTrueValue_= option.value_;
			}
			mTextField.staticTextField_.setText(option.label_);
			mTextField.staticTextField_.requestFocus();
			SelectView.selectV.ad_.dismiss();
			Select.ISRUNNING = false;
		}

		public FormLayout getForm() {
			// TODO Auto-generated method stub
			return selt_.formLayout_;
		}

		 protected void onDraw(Canvas canvas) {
			// 设置默认字体对其方式为居左
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			if (selt_.getText().toString().trim().equalsIgnoreCase(label_.trim())) {
				paint.setColor(ROW_TOUCH_BG_COLOR);
				canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
			}
			
			if (Utils.DM_DENSITY == 1) {
				paint.setTextSize(textSize_);
			} else {
				paint.setTextSize(Utils.getScaledValue(SELECT_FONT_SIZE_DEFAULT));
			}
			paint.setColor(textColor_);
			int y = (this.getHeight() + textSize_) >> 1;
			if (selt_.isCombobox_) {
				if (comboboxBitmap_ != null) {
					canvas.drawBitmap(comboboxBitmap_, this.getWidth()-Utils.getSystemScaledValue(50), 4, paint);
				}
				canvas.drawText(label_, 0, y, paint);
			} else {
				if (SelectView.select_.textAlign_.equalsIgnoreCase("left"))
					canvas.drawText(label_, 0, y, paint);
//              下拉框选项超宽时考虑用跑马灯的形式显示
//				StringTicker.instance().drawMoveStr(this, canvas, this.getWidth(), paint, textColor_, label_, 0, (int) y);
				else if (SelectView.select_.textAlign_
						.equalsIgnoreCase("right"))
					canvas.drawText(label_, this.getWidth()
							- (int) paint.measureText(label_), y, paint);
				else
					canvas.drawText(label_, (this.getWidth() - (int) paint
							.measureText(label_)) >> 1, y, paint);
			}
		}

		/**
		 * 响应触摸(Option)
		 * */
		public boolean onTouchEvent(MotionEvent event) {
			int touchEvent = event.getAction();
			int x = (int) event.getX();
			switch (touchEvent) {
			case MotionEvent.ACTION_DOWN:
				this.requestFocus();
				this.invalidate();
				break;
			case MotionEvent.ACTION_UP:
				int oldCurrentMenu = selt_.currentMenu_;
				if ((null != this.relaEnable_) || (null != this.relaDisable_) || (null != this.relaVisible_)
						|| (null != this.relaInvisible_) || (null != this.group_)) {
					// 设置控件点击效果
					selt_.currentMenu_ = selt_.dropdownMenuText_.indexOf(this);
					setText(this.label_);
					selt_.dropdownMenuClickItem();
					this.settleComponetOption(bv_, true, 0);
				} else if (null != this.selectSort_) {
					int viewCount = bv_.vWidgetArray_.size();
					Table table = null;
					Object o = null;
					for (int i = 0; i < viewCount; i++) {
						o = bv_.vWidgetArray_.elementAt(i);
						if (o instanceof Table) {
							table = (Table) o;
							if (table.attrName_.equals(selectSort_)) {
								break;
							}
						}
					}
				}
	
				SelectView.select_.setCurrentMenu(SelectView.select_.dropdownMenuText_.indexOf(this));
				
				if (selt_.isCombobox_) {
					if(x>getWidth()-50&&x<getWidth()-20){
						
						Select.Option optn = SelectView.select_.getCurrentOption();
						String allPhoneNumber = (String)Mid.saveProperty_.get(selt_.combobxOptionValueKey_);
						String delPhoneNumber ;
						if(mTextField.staticTextField_.mask_){
							delPhoneNumber =optn.value_.concat("#");
						} else {
							delPhoneNumber = optn.label_.concat("#");
						}
						allPhoneNumber = allPhoneNumber.replace(delPhoneNumber, "").trim();
						if (allPhoneNumber != "") {
							Mid.saveProperty_.put(selt_.combobxOptionValueKey_, allPhoneNumber);
						} else {
							Mid.saveProperty_.remove(selt_.combobxOptionValueKey_);
						}
						
						Utils.saveProperties();
						
						for (int nn = selt_.optionV_.size() - 1; nn >= 0; nn--) {
							Option op = (Option)selt_.optionV_.elementAt(nn);
							if (op.label_.equals(optn.label_)) {
								selt_.optionV_.removeElementAt(nn);
								break;
							}
						}
						selt_.resetDropdownMenuText(optn.ref_, true, selt_);
						
						SelectView.selectV.ad_.dismiss();
						Select.ISRUNNING = false;
						if (selt_.dropdownMenuText_.size() > 0) {
							mTextField.staticTextField_.setText(((Option)selt_.dropdownMenuText_.elementAt(0)).label_);
							Select.TouchWidthNormal(bv_, selt_);
						} else {
							mTextField.staticTextField_.isComlexbobox_ = false;
							mTextField.staticTextField_.setPadding(10, 0, 10, 0);
							mTextField.staticTextField_.setText("");
							return false;
						}
					} else {
						setTextField();
					}
					
				} else {
					setSelectView();
					
					if (oldCurrentMenu != selt_.currentMenu_ && selt_.actionUrl_ != null && !selt_.actionUrl_.trim().equals("")) {
//						执行网络请求，更新整个页面
						selt_.sendReqeuestBySelectOptionChange(selt_.actionUrl_, value_);
					}
				}
				SelectView.select_.invalidate();
				break;
			default:
				super.onTouchEvent(event);
			}
			return true;
		}

		// 按键操作
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				SelectView.selectV.ad_.dismiss();
				Select.ISRUNNING = false;
				break;
			default:
				return super.onKeyDown(keyCode, event);
			}
			return true;
		}

		@Override
		public void cleanText() {
			// TODO Auto-generated method stub

		}

		@Override
		public String getContentText() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public CssStyle getCssStyle() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getCmpHeight() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getCmpView() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getCmpWidth() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public boolean isInTable() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void mould() {
			// TODO Auto-generated method stub

		}

		@Override
		public void releaseResource(View view) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setContentText(String text) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setCssStyle(CssStyle style) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setEncrypt(String encrypt) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setForm(FormLayout formLayout) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setInTable(boolean inTable) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setCmpHeidht(int height) {
			// TODO Auto-generated method stub

		}

		@Override
		public void setCmpWidth(int width) {
			// TODO Auto-generated method stub

		}

		@Override
		public void shrinkWidth() {
			// TODO Auto-generated method stub

		}
	}

	static final class SelectLinearLayout extends LinearLayout {

		public SelectLinearLayout(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
			// this.setBackgroundResource(R.drawable.selectb);
			this.setGravity(Gravity.CENTER);
			this.setBackgroundColor(0);
		}

		protected void onDraw(Canvas canvas) {
			// 设置输出参数，该项操作本应在绘制域之前调用。此处调用纯属之前调用无效果无效果
			setLayout();
			if (null != backgroundImg_) {
				canvas.drawBitmap(backgroundImg_, 0, 0, new Paint());
			}
		}

		private void setLayout() {
			// TODO Auto-generated method stub
			ViewGroup.LayoutParams lp = this.getLayoutParams();
			if (null == lp) {
				lp = new LayoutParams(0, 0);
			}
			lp.width = backgroundImg_.getWidth();
			lp.height = backgroundImg_.getHeight();
			this.setLayoutParams(lp);
		}
	}

	Context context_;

	private LinearLayout selfLayout_;
	public static Bitmap arrowImg_;

	private static Bitmap backgroundImg_;
	private static int MARGIN_ARROW = 5;
	private static int textSize_ = ConfigManager.SIZE_MEDIUM;

	public Select(Context context, String text) {
		super(context);
		this.setFocusable(true);
		this.setFocusableInTouchMode(true);
		text_ = text;
		context_ = context;
		bv_ = (BaseView) context;
		dropdownMenuText_ = new Vector<Option>();
		font_ = new TextPaint();
		// 设置下拉菜单样式

		try {
			createImg(context);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}

		setGravity(Gravity.CENTER_VERTICAL);
	}

	public void sendReqeuestBySelectOptionChange(String actionUrl_2, String requestValue) {
		optionValue_ = requestValue;
		bv_.listener_.componentAction(this, bv_);
		
	}

	/**
	 * @param context
	 */
	private void createImg(Context context) throws Exception {
		/** Create button images */
		// Create arrow image.
		if (arrowImg_ == null) {
			arrowImg_ = null;
			arrowImg_ = ConstantRepository.decodeBitmap(context.getResources(), R.drawable.select_arr);
		}
	}

	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	/**
	 * 通过将要显示的字符串来得到下拉框控件的选择项，如果找不到该项，则返回下拉框控件的默认项
	 * 
	 * @param str
	 * @return
	 */
	public Select.Option getOption(String str) {
		if (null == str || str.equals("")) {
			return (Option) this.dropdownMenuText_.elementAt(this.currentMenu_);
		} else {
			final int size = this.dropdownMenuText_.size();
			Select.Option option = null;
			for (int i = 0; i < size; i++) {
				// 循环遍历下拉框元素的显示项
				option = (Option) this.dropdownMenuText_.elementAt(i);
				if (str.equalsIgnoreCase(option.label_)) {
					currentMenu_ = i;
					return option;
				}
			}
			return (Option) this.dropdownMenuText_.elementAt(this.currentMenu_);
		}
	}

	public void setText(String str) {
		super.setText(str);
		text_ = str;
	}

	public void setCurrentMenu(int index) {
		currentMenu_ = 0;
		if (index >= 0 && index < ddmSize_)
			currentMenu_ = index;
	}

	public Option getCurrentOption() {
		Option currentOption = null;
		try {
			if (dropdownMenuText_ != null && dropdownMenuText_.size() > 0 && dropdownMenuText_.size() > currentMenu_){
				currentOption = (Option) dropdownMenuText_.elementAt(currentMenu_);
			} 
		} catch (Exception ex) {
			Utils.printException(ex);
		}
		return currentOption;
	}

	// 初始化从xml中读取的下拉框控件可选值
	static Option initOption(BaseView bv, String text, String selectSort, String sortKey, String select, String value,
			String group, String ref, String[] relaEnable, String[] relaDisable, String[] relaVisible,
			String[] relaInvisible) {
		Option o = new Option(bv, text);
		o.selectSort_ = selectSort;
		o.sortKey_ = sortKey;
		o.select_ = select;
		o.value_ = value;
		o.group_ = group;
		o.ref_ = ref;
		o.relaEnable_ = relaEnable;
		o.relaDisable_ = relaDisable;
		o.relaVisible_ = relaVisible;
		o.relaInvisible_ = relaInvisible;
		return o;
	}

	void setDropdownMenuText(Option o) {
		String ref = o.ref_;
		if (ref == null || groupN_ == null || ref.equals(groupN_)) {
			groupN_ = ref;
			addDropdownOption(o);
		}
		addOption(o);
	}

	void setOption(Vector<Option> vector) {
		if (optionV_ == null)
			optionV_ = new Vector<Option>();
		optionV_ = vector;
	}

	void addDropdownOption(Option o) {
		ddmSize_++;
		dropdownMenuText_.addElement(o);
		BaseView.setTypeFace(font_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		ddmMaxWidth_ = (int) Math.max(ddmMaxWidth_, font_.measureText(o.label_));
		// should not bigger than maxWidth_, here decrease 32 is 12 + 18 + 2,12
		// is the triangle width and 18 is blank and 2 for margin.
		if (ddmMaxWidth_ > width_ - 32)
			ddmMaxWidth_ = width_ - 32;
		ddmTotalHeight_ += getStringLineHeight() + BaseView.ITEM_MARGIN;
	}

	void addOption(Option o) {
		if (optionV_ == null)
			optionV_ = new Vector<Option>();
		optionV_.addElement(o);
	}

	void resetDropdownMenuText(String group, boolean refresh, Select s) {
		if (refresh){
			dropdownMenuText_.removeAllElements();
			ddmSize_ = 0;
			ddmMaxWidth_ = ddmTotalHeight_ = 0;
			setCurrentMenu(0);
			width_ = MAX_WIDTH;
			for (int i = 0; i < optionV_.size(); i++) {
				Option o = (Option) optionV_.elementAt(i);
					addDropdownOption(o);
			}
			settleRelationAction();
		} else if (optionV_ != null && group != null && !group.equals(groupN_)) {
			groupN_ = group;
			text_ = null;
			dropdownMenuText_.removeAllElements();
			ddmSize_ = 0;
			// ddmMaxWidth_ = ddmTotalHeight_ = ddmXStar_ = ddmYStar_ = 0;
			ddmMaxWidth_ = ddmTotalHeight_ = 0;
			setCurrentMenu(0);
			// settleRelationAction(); //modify 2009-04-22
			// bv_.reCalculateTotalWH(); // have do it in
			// dropdownMenuClickItem().
			width_ = MAX_WIDTH;
			for (int i = 0; i < optionV_.size(); i++) {
				Option o = (Option) optionV_.elementAt(i);
				if (o.ref_ == null || group.equals(o.ref_)) {
					addDropdownOption(o);
					if (text_ == null) {
						text_ = o.label_; // defaultText
						updateOtherMenu(o.group_);
					}
					if (o.select_ != null && group.equals(o.ref_) && o.select_.equals("selected")){
						setCurrentMenu(ddmSize_-1);
						text_ = o.label_;
						updateOtherMenu(o.group_);
					}
				}
			}
			s.setText(text_);
			settleRelationAction();
		}
	}

	public void settleRelationAction() {
		try {
			boolean isChecked = false;
			Option currentOption = getCurrentOption();
			Option tempOption = null;
			for (int j = 0; j < optionV_.size(); j++) {
				isChecked = false;
				tempOption = (Option) optionV_.elementAt(j);
				if (currentOption == tempOption)
					continue;
				settleRelationAction(tempOption, isChecked);
			}
			isChecked = true;
			settleRelationAction(currentOption, isChecked);
		} catch (Exception ex) {
		}
	}

	private void settleRelationAction(Option option, boolean isChecked) {
		setRelative(option);
	}

	public void dropdownMenuClickItem() {
		if (this.isShown()) {
			Option o = (Option) dropdownMenuText_.elementAt(currentMenu_);
			updateOtherMenu(o.group_, o.selt_.attrRName_);
			settleRelationAction();
		}
	}

	private void setRelative(Option optn) {
		try {
			relaEnable_ = optn.relaEnable_;
			relaDisable_ = optn.relaDisable_;
			relaVisible_ = optn.relaVisible_;
			relaInvisible_ = optn.relaInvisible_;
		} catch (Exception ex) {
			Utils.printException(ex);
		}
	}

	private void updateOtherMenu(String group, String name) {
		if (group != null && bv_ != null) {
			int sz = bv_.vWidgetArray_.size();
			for (int i = 0; i < sz; i++) {
				Object o = bv_.vWidgetArray_.elementAt(i);
				if (o instanceof Wrap)
					continue;
				View c = (View) o;
				if (c instanceof Select && c != this) {
					Select s = (Select) c;
					if ((name != null) && (s.attrName_ != null)) {
						if (name.equals(s.attrName_)) {
							s.resetDropdownMenuText(group, false, s);
						}
					} else {
						if (s.isRefWithGroup(group)) {
							s.resetDropdownMenuText(group, false, s);
						}
					}

				}
			}
		}
	}
	/** update other menu which have ref */
	private void updateOtherMenu(String group) {
		if (group != null && bv_ != null) {
			int sz = bv_.vWidgetArray_.size();
			for (int i = 0; i < sz; i++) {
				Object o = bv_.vWidgetArray_.elementAt(i);
				if (o instanceof Wrap)
					continue;
				View c = (View) o;
				if (c instanceof Select && c != this) {
					Select s = (Select) c;
					if (s.isRefWithGroup(group))
						s.resetDropdownMenuText(group, false, s);
				}
			}
		}
	}

	public void cleanText() {
		// repuplate the other when it is changed
		if (this.isShown()) {
			Option o = (Option) dropdownMenuText_.elementAt(currentMenu_);
			setText(o.label_);
			updateOtherMenu(o.group_);
			settleRelationAction();
		}
	}

	private boolean isRefWithGroup(String group) {
		if (optionV_ != null && group != null) {
			for (int i = optionV_.size() - 1; i >= 0; i--) {
				Option o = (Option) optionV_.elementAt(i);
				if (group.equals(o.ref_)) {
					return true;
				}
			}
		}
		return false;
	}

	
/*	private boolean isRefWithGroup(String group, String name) {
		if (optionV_ != null && group != null && name != null) {
			for (int i = optionV_.size() - 1; i >= 0; i--) {
				Option o = (Option) optionV_.elementAt(i);
				if (group.equals(o.ref_) && name.equals(o.lps_.attrName_)) {
					return true;
				}
			}
		}
		return false;
	}*/
	// Set the drop down menu Text one by one and calculate the max value of
	// Text width.
	public void setDropdownMenuText(String text) {
		Option o = new Option(bv_, text);
		addDropdownOption(o);
	}

	/**
	 * Returns the height of one string line.
	 */
	protected int getStringLineHeight() {
		return (int) (((font_ == null) ? 0 : font_.getTextSize()) + 2 * Y_MARGIN);
	}

	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	// 根据包含的字符串长度设置该控件的宽高值
	void setLayoutParams() {
		LayoutParams lllp = (LayoutParams) this.getLayoutParams();
		if (null == lllp) {
			lllp = new LayoutParams(0, 0);
		}
		int size = dropdownMenuText_.size();
		int length;
		int lengthMax = 0;
		TextPaint paint = new TextPaint();
		paint.setTextSize(Utils.getScaledValue(16));
		BaseView.setTypeFace(paint, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		for (int i = 0; i < size; i++) {
			length = (int) paint.measureText(((Option) dropdownMenuText_.get(i)).label_);
			lengthMax = Math.max(length, lengthMax);
		}
		lllp.width = (int) (lengthMax << 1) + arrowImg_.getWidth() + 2 * MARGIN_ARROW;
		lllp.height = (int) paint.getTextSize() << 1;
		super.setLayoutParams(lllp);

		try {
			// createSelect(lllp.width, activeButtonImg_, inactiveButtonImg_);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
	}

	public static void TouchWidthAccessory(BaseView parent, Select select, String accessory) {
		// 如果该属性可取值，则不执行原有的下拉框弹出操作
		String nameDive = accessory.substring(accessory.indexOf(":") + 3);
		// 根据名字在哈希表中找到需要的控件集合
		ArrayList<Component> views = parent.invisibleViews_.get(nameDive);
	}

	public static void TouchWidthNormal(BaseView parent, Select select) {
		int size = select.dropdownMenuText_.size();
		View[] views = new View[size];
		for (int i = 0; i < size; i++) {
			views[i] = (View) select.dropdownMenuText_.get(i);
		}
		SelectView.selectV = SelectView.getInstance(parent, views);
		SelectView.selectV.setSelectView(select);
	}

	/**
	 * 触摸响应（Select）
	 */
	public boolean onTouchEvent(MotionEvent me) {
		int action = me.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			this.setPressed(true);
			this.invalidate();
			super.onTouchEvent(me);
			break;
		case MotionEvent.ACTION_UP:
			this.requestFocus();
			this.invalidate();
			if (!Select.ISRUNNING) {
				Select.ISRUNNING = true;
				if ((null != attrAccessory_) && (!attrAccessory_.equals(""))) {
					if (attrAccessory_.startsWith("cusv_select://")) {
						// 找到需要联动的div
						String nameDive = attrAccessory_.substring(attrAccessory_.indexOf(":") + 3);
						ArrayList<Component> views = bv_.invisibleViews_.get(nameDive);
						if (null != views && views.size() > 0) {
							views = null;
							TouchWidthAccessory(bv_, this, attrAccessory_);
						}
					} else if ("wheel_select://date".equals(attrAccessory_)) {
						// 显示日期
						showPickerDialog();
					}
				} else {
					TouchWidthNormal(bv_, this);
				}
			}
			super.onTouchEvent(me);
			break;
		default:
			super.onTouchEvent(me);
			break;
		}

		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int action = event.getAction();
		// 上下左右响应该控件的原始效果
		if ((keyCode == KeyEvent.KEYCODE_DPAD_UP) || (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) || (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) || (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) || (keyCode == KeyEvent.KEYCODE_BACK)) {
			return super.onKeyDown(keyCode, event);
		}
		if ((null != attrAccessory_) && (!attrAccessory_.equals(""))) {
			switch (action) {
			case KeyEvent.ACTION_UP:
				if (!Select.ISRUNNING) {
					Select.ISRUNNING = true;
					TouchWidthAccessory(bv_, this, attrAccessory_);
				}
				break;
			case KeyEvent.ACTION_DOWN:
				if (!Select.ISRUNNING) {
					Select.ISRUNNING = true;
					if ("wheel_select://date".equals(attrAccessory_)) {
						// 显示日期
						showPickerDialog();
					}
				}
				break;
			default:
				return super.onKeyDown(keyCode, event);
			}
		} else {
			switch (action) {
			case MotionEvent.ACTION_DOWN:
				if (!Select.ISRUNNING) {
					TouchWidthNormal(bv_, this);
				}
				break;
			default:
				return super.onKeyDown(keyCode, event);
			}
		}
		return true;
	}

	public void mould() {
		TextPaint paint;
		if (isCombobox_) {
			setLayoutParams(new LinearLayout.LayoutParams(35, 35));
			return;
		}
		if (cssStyle_ != null) {
			if (null != cssStyle_.textAlign_) {
				textAlign_ = cssStyle_.textAlign_;
			}
			if (cssStyle_.fgColor_ != 0) {
				textColor_ = cssStyle_.fgColor_;
			}
			if (cssStyle_.fontSize_ > 0) {
				textSize_ = cssStyle_.fontSize_;
			}

			paint = new TextPaint();
			paint.setTextSize(textSize_);

			if (cssStyle_.width_ >= 0) {
				width_ = cssStyle_.width_;
			}

			// set the font family (since API Level 4)
			/*
			 * String fontPath = ConfigManager.getFontPath(cbStyle.fontFamily_); if (fontPath != null) {
			 * temp.setTypeface(Typeface.createFromFile(fontPath)); }
			 */

			if (cssStyle_.height_ >= 0) {
				height_ = cssStyle_.height_;
			} else {
//				height_ = textSize_ + (textBlank_ << 1);
				height_ = Utils.getSystemScaledValue(40);
			}
			// set the background color.
			if (cssStyle_.bgColor_ != 0) {
				bgColor_ = cssStyle_.bgColor_;
			}
		} else {
			paint = new TextPaint();
			paint.setTextSize(textSize_);
			height_ = textSize_ + (textBlank_ << 1);
		}
		paint.setTextSize(Utils.getScaledValue(SELECT_FONT_SIZE_DEFAULT));

		if ((null == textAlign_) || (textAlign_.equals(""))) {
			textAlign_ = "left";
		}
		BaseView.setTypeFace(paint, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		// 设置弹出框控件中option中的控件字体大小
		int optionSize;
		if (this.optionV_ != null){
			optionSize = this.optionV_.size();
		} else {
			optionSize = 0;
		}
		
		for (int i = 0; i < optionSize; i++) {
			Select.Option option = (Select.Option) optionV_.get(i);
			option.setTextSize(textSize_);
			option.setTextColor(textColor_);
		}

		if (width_ <= 0) {
			selectMaxWidth_ = MAX_WIDTH * 9 / 10 - offsetLength; //MAX_WIDTH / 10约为右边距+箭头宽度
			
			// 说明服务端未指定该控件的宽度值,将遍历出的宽度值赋值给width_
			// 遍历下拉框控件的所有元素，确定最大宽度值
			int length = 0;
			int size = optionV_.size();
			for (int i = 0; i < size; i++) {
				length = (int) Math.max(length,
						paint.measureText(((Select.Option) optionV_.elementAt(i)).label_));
			}
			length = length > selectMaxWidth_ ? selectMaxWidth_ : length;
			
			// 如果有与该控件相关联的隐藏div，则需要遍历所有的div宽度，来确定宽度值。
			if ((null != attrAccessory_) && (!attrAccessory_.equals(""))) {
				// 获取与之相关联的div名称
				String nameDive = attrAccessory_.substring(attrAccessory_.indexOf(":") + 3);
				// 根据名字在哈希表中找到需要的控件集合
				try {
					if (null != bv_.invisibleViews_) {
						ArrayList<Component> views = bv_.invisibleViews_.get(nameDive);
						for (int i = 0; i < views.size(); i++) {
							View temp;
							try {
								temp = (View) views.get(i);
							} catch (Exception e) {
								continue;
							}
							// 该处暂定单选控件显示内容为与下拉框控件需显示内容相关
							if (temp instanceof Radio) {
								Radio radio = (Radio) temp;
								if (null != radio.getText().toString()) {
									length = (int) Math.max(length, paint.measureText(radio.getText().toString()));
								}
							}
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Utils.printException(e);
				}
			}
			if(null != attrAccessory_ && attrAccessory_.equals("cusv_select://shopSign") && null != arrowImg_) {
				if(null == dropdownIcon_) {
					dropdownIcon_ = ConstantRepository.decodeBitmap(this.getResources(), R.drawable.grayspot);
				}
				width_ = (int) (length + paint.measureText("京")); //取1个字符宽度作为点图片和边距宽度的总和
			} else {
				width_ = length;
			}
		} else{
			if (null != selectIcon_){
				if(null == arrowIcon_) {
					arrowIcon_ = ConstantRepository.decodeBitmap(this.getResources(), R.drawable.select_arr);
				}
				width_ += (int) (paint.measureText("金"));
			}
			selectMaxWidth_ = width_;
		}

		LinearLayout.LayoutParams vgl = null;
		try {
			vgl = (LayoutParams) getLayoutParams();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
		if (null == vgl) {
			vgl = new LinearLayout.LayoutParams(0, 0);
		}

		// 确定宽后,按宽度确定背景图片
		backgroundBitmap_ = mButton.createImg(bv_, R.drawable.select_all);

		vgl.width = width_ + 8;
		if (this.isInTable_)
			vgl.height = height_;
		else
			vgl.height = backgroundBitmap_[0].getHeight();
		this.setLayoutParams(vgl);

		if (!this.isInTable_) {
			// 准备该控件不在表格中时该显示的元素资源
			backgroundBitmap_ = this.createBackground(width_, backgroundBitmap_);

			if (selfLayout_ != null) {
				BaseView.removeViewsStepByStep(selfLayout_, this);
			}
			selfLayout_ = BaseView.createSelfLayout(bv_, vgl, cssStyle_, this);
		}
	}


	protected void onDraw(Canvas canvas) {
		if (isInTable_) {
			drawInTable(canvas);
		} else if (isCombobox_) {
			drawComboboxButton(canvas);
		} else {
			drawInNormal(canvas);
		}
	}

	private void drawComboboxButton(Canvas canvas) {
		if (arrowImg_ != null) {
			canvas.drawBitmap(arrowImg_, (35 - arrowImg_.getWidth()) >> 1,
					(35 - arrowImg_.getHeight()) >> 1, font_);
		}
	}

	private void drawInNormal(Canvas canvas) {
		// TODO Auto-generated method stub
		TextPaint paint = new TextPaint();
		paint.setAntiAlias(true);
		// draw background
		Bitmap bitmap = null;
		if (isFocused()) {
			bitmap = backgroundBitmap_[mButton.FOCUS_IMG];
		} else if (this.isPressed()) {
			bitmap = backgroundBitmap_[mButton.FOCUS_IMG];
		} else {
			bitmap = backgroundBitmap_[mButton.NORMAL_IMG];
		}
		canvas.drawBitmap(bitmap, 0, 0, paint);
		// 背景图宽
		int bitmapW = bitmap.getWidth();
		// 箭头宽
		int arrSelectW = Constant.arrSelect_.getWidth();
		// 文字宽
		int textW = 0;
		if (text_.indexOf("...") != -1) {// paint好像计算不出来“...”的宽
			textW = (int) (paint.measureText(text_) + paint.getTextSize());
		} else {
			textW = (int) paint.measureText(text_);
		}

		// 画文字的x起始坐标
		int drawTextX = 0;
		// 画字体
		paint.setTextSize(Utils.getScaledValue(SELECT_FONT_SIZE_DEFAULT));
		paint.setColor(textColor_);
		BaseView.setTypeFace(paint, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		if (cssStyle_ != null && cssStyle_.textAlign_ != null) {
			if (cssStyle_.textAlign_.equalsIgnoreCase("center")) {
				drawTextX = (bitmapW - arrSelectW - textW - 5) >> 1;
			} else if (cssStyle_.textAlign_.equalsIgnoreCase("right")) {
				drawTextX = (bitmapW - arrSelectW - textW - 5);
			} else {// left

			}
		}
		canvas.drawText(text_, drawTextX, ((height_ + SELECT_FONT_SIZE_DEFAULT) >> 1), paint);

		canvas.drawBitmap(Constant.arrSelect_, width_ - Constant.arrSelect_.getWidth() - 5,
				((height_ - Constant.arrSelect_.getHeight()) >> 1) + 5, paint);
	}

	private void drawInTable(Canvas canvas) {
		TextPaint paint = new TextPaint();
		paint.setAntiAlias(true);
		// 画字体
		paint.setTextSize(Utils.getScaledValue(SELECT_FONT_SIZE_DEFAULT));
		paint.setColor(textColor_);
		BaseView.setTypeFace(paint, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		int count = text_.length() - 1;
		if (paint.measureText(text_) > selectMaxWidth_) {
			String text = text_.substring(0, count);
			while(paint.measureText(text) > selectMaxWidth_){
				count--;
				text = text_.substring(0, count);
			}

			if (null != selectIcon_ && selectIcon_.equals("arrow.png")&& null != arrowIcon_){
				canvas.drawText(text_.substring(0, count-1), 0, height_/ 2 - 2, paint);
				canvas.drawText(text_.substring(count-1), 0, height_ - 3, paint);
				canvas.drawBitmap(arrowIcon_, paint.measureText(text_.substring(0, count))-2, (height_ - arrowIcon_.getHeight()) >> 1, paint);
			} else{
				canvas.drawText(text_.substring(0, count), 0, height_/ 2 - 2, paint);
				canvas.drawText(text_.substring(count), 0, height_ - 3, paint);
			}
		} else {
			canvas.drawText(text_, 0, (((height_ + (int) paint.getTextSize()) >> 1) - 1), paint);
			if(null != attrAccessory_ && attrAccessory_.equals("cusv_select://shopSign") && null != dropdownIcon_) {
				canvas.drawBitmap(dropdownIcon_, paint.measureText("京") * 3 / 2, (height_ - dropdownIcon_.getHeight()) >> 1, paint);
			}
		}
	}

	void clear() {
		dropdownMenuText_.removeAllElements();
	}

	/**
	 * @param buttonWidth
	 * @param buttonHeight
	 */
	private Bitmap[] createBackground(int buttonWidth, Bitmap[] backgroundBitmap) {
		int size = backgroundBitmap.length;
		for (int i = 0; i < size; i++) {
			try {
				backgroundBitmap[i] = Utils.makeButton(backgroundBitmap[i], buttonWidth);
			} catch (Exception e) {
				Utils.printException(e);
			}
		}
		return backgroundBitmap;
	}

	public void setCmpHeidht(int height) {

	}

	public void setCmpWidth(int width) {

	}

	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	public View getCmpView() {
		if (selfLayout_ != null) {
			return selfLayout_;
		}
		return this;
	}

	public int getCmpHeight() {
		return height_;
	}

	public int getCmpWidth() {
		return width_;
	}

	public void setInTable(boolean inTable) {
		isInTable_ = inTable;
	}

	public boolean isInTable() {
		return isInTable_;
	}

	public CssStyle getCssStyle() {
		return cssStyle_;
	}

	public void releaseResource(View view) {
		if (null != arrImg_ && !arrImg_.isRecycled())
			arrImg_.recycle();
		arrImg_ = null;
	}

	public void setForm(FormLayout formLayout) {
		formLayout_ = formLayout;
	}

	public FormLayout getForm() {
		return formLayout_;
	}

	@Override
	public void setEncrypt(String encrypt) {
		isEncrypt_ = encrypt;
	}
	
	
	public void showPickerDialog() {
		if (initDataComplete) {
			pickerDialog.show();
		} else {
			initPickerDialog();
			pickerDialog.show();
		}
	}
	
	public void initPickerDialog() {
		visiableItems = 5;

		dayPicker = new WheelView(bv_);
		dayPicker.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_ * 3 / 10, LinearLayout.LayoutParams.WRAP_CONTENT));
		dayPicker.setVisibleItems(visiableItems);
		dayPicker.setAdapter(new ArrayWheelAdapter<String>(dayNames));
		
		hourPicker = new WheelView(bv_);
		hourPicker.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_ * 3 / 10, LinearLayout.LayoutParams.WRAP_CONTENT));
		hourPicker.setVisibleItems(visiableItems);
		hourPicker.setAdapter(new ArrayWheelAdapter<String>(hourNames));
		
		minPicker = new WheelView(bv_);
		minPicker.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_ * 3 / 10, LinearLayout.LayoutParams.WRAP_CONTENT));
		minPicker.setVisibleItems(visiableItems);
		minPicker.setAdapter(new ArrayWheelAdapter<String>(minNames));
		
		dayPicker.setCurrentItem(dayCurrentItem);
		
		// 布局
		pickerLayout = new LinearLayout(bv_);
		pickerContainer = new LinearLayout(bv_);
		titleLayout = new LinearLayout(bv_);
		pickerLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		titleLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		pickerContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		titleLayout.setGravity(Gravity.RIGHT);
		pickerLayout.setOrientation(LinearLayout.VERTICAL);
		titleLayout.setOrientation(LinearLayout.HORIZONTAL);
		pickerContainer.setOrientation(LinearLayout.HORIZONTAL);
		
		Button okBtn = new Button(bv_);
		okBtn.setWidth(20);
		okBtn.setHeight(20);
		okBtn.setBackgroundResource(R.drawable.delete);
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int dayId = dayPicker.getCurrentItem();// 日id
				int hourId = hourPicker.getCurrentItem();// 时id
				int minId = minPicker.getCurrentItem();// 分id
				String label = dayNames[dayId].concat("_").concat(hourNames[hourId]).concat("_").concat(minNames[minId]) ;// Select显示的label
				String value = dayNames[dayId].concat("_").concat(hourNames[hourId]).concat("_").concat(minNames[minId]); // Select递交的value
				
				// 记住当前选择的大类id,用于返回页面缓存
				dayCurrentItem = dayId;
				
				// 界面显示
				Select.this.setText(label);
				Select.Option option = (Select.Option) Select.this.optionV_.elementAt(0);
				option.setValue(value);
				pickerDialog.dismiss();
				ISRUNNING = false;
			}
		});
		titleLayout.addView(okBtn);
		
		pickerContainer.addView(dayPicker);
		pickerContainer.addView(hourPicker);
		pickerContainer.addView(minPicker);
		
		pickerLayout.addView(titleLayout);
		pickerLayout.addView(pickerContainer);
		// 弹出
		pickerDialog = new AlertDialog.Builder(bv_).create();
		Window window = pickerDialog.getWindow();
		window.setLayout(480, 480);
		window.setGravity(Gravity.BOTTOM);
		pickerDialog.setView(pickerLayout);
		pickerDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				ISRUNNING = false;
			}
		});
		initDataComplete = true;
	}
	
	
}
